'use strict';

/**
 * 根据b站昵称登录
 */
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event);
	
	let nickName = event.nickname;
	// 请求接口，查询昵称是否存在
	let nickNameUrl = "http://passport.bilibili.com/web/generic/check/nickname";
	const apiRes = await uniCloud.httpclient.request(nickNameUrl, {
		method: "GET",
		data: {
			nickName: nickName,
		},
		dataType: 'json' 
	});
	console.log("请求昵称接口返回：", apiRes);
	let resData = apiRes.data;
	console.log("请求昵称接口返回，内容：", resData);
	
	// 如果昵称不被他人使用，且昵称不存在，则登录失败
	if (resData.code !== 2001 && resData.code !== 40014) {
		return {
			code: -1,
			message: '昵称可能不存在哦，请再确认一下？',
		};
	}
	
	
	// 获取数据库中昵称记录
	const db = uniCloud.database();
	let userRecordRes = await db.collection("uni-id-users").where({_id: nickName}).get();
	console.log("数据库中记录：", userRecordRes);
	
	//不存在则保存
	if (userRecordRes && userRecordRes.data.length <= 0) {
		//保存
		let res = await db.collection("uni-id-users").add({
			_id: nickName,
			username: nickName,
			nickname: nickName,
		});
		console.log("插入记录结果：", res);
		userRecordRes = res;
	} else {
		userRecordRes = userRecordRes.data[0];
	}
	
	//返回数据给客户端
	return {
		code: 200,
		data: userRecordRes,
		message: "ok"
	};
};
